package edu.neu.cloud_factory.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import edu.neu.cloud_factory.entity.po.Factory;
import edu.neu.cloud_factory.dao.FactoryMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.neu.cloud_factory.entity.po.User;
import edu.neu.cloud_factory.entity.vo.FactoryVo;
import edu.neu.cloud_factory.entity.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 工厂 服务实现类
 * </p>
 *
 * @author halozhy
 * @since 2021-07-15
 */
@Service
public class FactoryService extends ServiceImpl<FactoryMapper, Factory> implements IService<Factory> {

    @Autowired
    FactoryMapper factoryMapper;

    public JSONObject listFac(int page, int limit, String id, String name, String describe) {
        QueryWrapper<Factory> queryWrapper = new QueryWrapper<>();
        if (id != null && !id.isEmpty()) {
            queryWrapper.like("f_id", id);
        }
        if (name != null && !name.isEmpty()) {
            queryWrapper.like("f_name", name);
        }
        if (describe != null && !describe.isEmpty()) {
            queryWrapper.like("f_describe", describe);
        }

        List<Factory> factoryListList = factoryMapper.listPage((page - 1) * limit, limit, queryWrapper);
        List<FactoryVo> factoryVoList = new ArrayList<>();
        factoryListList.forEach(factory -> {
            FactoryVo factoryVo = new FactoryVo();
            factoryVo.setId(factory.getFId());
            factoryVo.setName(factory.getFName());
            factoryVo.setDescribe(factory.getFDescribe());
            factoryVo.setState(factory.getFState());
            factoryVoList.add(factoryVo);
        });
        JSONObject result = new JSONObject();
        result.put("data", factoryVoList);
        result.put("count", factoryMapper.selectCount(queryWrapper));
        return result;
    }

    /**
     * 关停工厂
     *
     * @param id 工厂id
     * @return 0 ok -1 无此工厂 -2 此工厂已经被关停
     */
    public int shutdown(Integer id) {
        return changeFacState(id, "正常", "关停");
    }

    /**
     * 开启工厂
     *
     * @param id 工厂id
     * @return 0 ok -1 无此工厂 -2 此工厂已经开启
     */
    public int open(Integer id) {
        return changeFacState(id, "关停", "正常");
    }

    private int changeFacState(Integer id, String original, String newState) {
        // 先get，然后修改状态为 新状态
        Factory f = factoryMapper.selectById(id);
        if (f == null) {
            return -1;
        } else {
            if (f.getFState().equals(original)) {
                f.setFState(newState);
                factoryMapper.updateById(f);
                return 0;
            } else {
                return -2;
            }
        }
    }
}
